package cn.iocoder.yudao.module.picturebook.service.bookcontext;

import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.translation.TranslationDO;
import cn.iocoder.yudao.module.picturebook.dal.mysql.book.BookMapper;
import cn.iocoder.yudao.module.picturebook.dal.mysql.translation.TranslationMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;

import cn.iocoder.yudao.module.picturebook.controller.admin.bookcontext.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.bookcontext.BookContextDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.bookcontext.BookContextMapper;

/**
 * 绘本内容表	 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class BookContextServiceImpl implements BookContextService {

    @Resource
    private BookContextMapper bookContextMapper;
    @Resource
    private BookMapper bookMapper;

    @Resource
    private TranslationMapper translationMapper;

    // ... existing code ...
    @Override
    public String createBookContext(BookContextSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            return null;
        }

        // 插入
        BookContextDO bookContext = BeanUtils.toBean(createReqVO, BookContextDO.class);
        bookContextMapper.insert(bookContext);

        // 返回
        return bookContext.getBookId();
    }

    @Override
    public void updateBookContext(BookContextSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            return;
        }
        if (updateReqVO.getBookId() == null || updateReqVO.getBookId().isEmpty()) {
            return;
        }

        // 校验存在
        if (bookContextMapper.selectById(updateReqVO.getBookId()) == null) {
            return;
        }
        // 更新
        BookContextDO updateObj = BeanUtils.toBean(updateReqVO, BookContextDO.class);
        bookContextMapper.updateById(updateObj);
    }

    @Override
    public void deleteBookContext(String id) {
        // 参数校验
        if (id == null || id.isEmpty()) {
            return;
        }

        // 校验存在
        if (bookContextMapper.selectById(id) == null) {
            return;
        }
        // 删除
        bookContextMapper.deleteById(id);
    }

    @Override
    public void deleteBookContextListByIds(List<String> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            return;
        }

        // 删除
        bookContextMapper.deleteByIds(ids);
    }


    private void validateBookContextExists(String id) {
        // 参数校验
        if (id == null || id.isEmpty()) {
            return;
        }

        if (bookContextMapper.selectById(id) == null) {
            // 不抛出异常，仅记录日志
            log.error("[getBookContext][id({}) 不存在]", id);
        }
    }

    @Override
    public BookContextRespVO getBookContext(String id) {
        // 参数校验
        if (id == null || id.isEmpty()) {
            return null;
        }

        // 查询绘本上下文
        BookContextDO bookContextDO = bookContextMapper.selectById(id);
        if (bookContextDO == null) {
            return null;
        }

        // 转换为VO对象
        BookContextRespVO bookContextRespVO = BeanUtils.toBean(bookContextDO, BookContextRespVO.class);

        // 获取绘本信息
        BookDO bookDO = bookMapper.selectById(bookContextDO.getBookId());
        if (bookDO != null) {
            bookContextRespVO.setBookName(bookDO.getTitle());
        }

        // 获取绘本的翻译
        List<TranslationDO> translationList = null;
        try {
            translationList = translationMapper.selectByBookId(bookContextDO.getBookId());
        } catch (Exception e) {
            // 获取翻译信息失败，继续处理
            log.error("[getBookContext][id({}) 获取翻译信息失败]", id, e);
        }

        try {
            // 解析绘本内容
            String context = bookContextRespVO.getContext();
            if (context != null && !context.isEmpty()) {
                // 解析JSON内容
                JSONObject contextJson = JSONObject.parseObject(context);
                JSONArray mediaList = contextJson.getJSONArray("media_list");

                // 添加空值检查
                if (mediaList == null) {
                    bookContextRespVO.setContext("[]"); // 返回空数组
                    return bookContextRespVO;
                }

                // 构建页码到翻译的映射
                Map<String, TranslationDO> translationMap = new HashMap<>();
                if (translationList != null) {
                    for (TranslationDO translation : translationList) {
                        if (translation != null && translation.getCurrentPage() != null) {
                            translationMap.put(String.valueOf(translation.getCurrentPage()), translation);
                        }
                    }
                }

                // 处理每一页的媒体资源，添加翻译信息
                List<Map<String, Object>> processedMediaList = new ArrayList<>();
                for (int i = 0; i < mediaList.size(); i++) {
                    JSONObject mediaItem = mediaList.getJSONObject(i);
                    if (mediaItem != null) {
                        String pageNum = mediaItem.getString("currentPage");

                        // 如果是有效的页面项（排除total项）
                        if (pageNum != null) {
                            // 创建一个新的Map来存储处理后的页面数据
                            Map<String, Object> pageData = new HashMap<>();
                            pageData.put("audioUrl", mediaItem.getString("audio_url"));
                            pageData.put("imageUrl", mediaItem.getString("image_url"));
                            pageData.put("pageNum", pageNum);

                            // 添加翻译信息
                            TranslationDO translation = translationMap.get(pageNum);
                            if (translation != null) {
                                pageData.put("chineseTranslation", translation.getChinese());
                                pageData.put("englishTranslation", translation.getEnglish());
                            }

                            processedMediaList.add(pageData);
                        }
                    }
                }

                // 将处理后的媒体列表转换为JSON字符串并设置回VO
                String processedContext = JSONObject.toJSONString(processedMediaList);
                bookContextRespVO.setContext(processedContext);
            }
        } catch (Exception e) {
            // JSON解析失败，返回原始内容或空内容
            bookContextRespVO.setContext("[]");
            log.error("[getBookContext][id({}) JSON解析失败]", id, e);
        }

        return bookContextRespVO;
    }


    @Override
    public PageResult<BookContextDO> getBookContextPage(BookContextPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            return PageResult.empty();
        }

        return bookContextMapper.selectPage(pageReqVO);
    }


}